//Copyright (c) 2013 Tilo Szepan 
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
//documentation files (the "Software"), to deal in the Software without restriction, including without limitation
//the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
//and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

//The above copyright notice and this permission notice shall be included in all copies or substantial portions 
//of the Software.

//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
//TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
//THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
//CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
//DEALINGS IN THE SOFTWARE.

using System;
using System.Text;
using System.Collections.Specialized;
using MonoMac;
using MonoMac.AppKit;
using MonoMac.Foundation;

namespace DuinoClient
{
	public class MacHelper : NSObject
	{
		public void SetClipboard(StringCollection files)
		{
			// to avoid memory leaks:
			InvokeOnMainThread(()=>{
				var pb = NSPasteboard.GeneralPasteboard;
				pb.ClearContents();
				pb.SetDataForType(FilesToData(files), NSPasteboard.NSFilenamesType);
				var sb = new StringBuilder();
				foreach(var f in files){
					sb.Append(f);
					sb.Append("\n");
				}
				pb.SetStringForType(sb.ToString(), NSPasteboard.NSStringType);
			});
		}
		public NSData FilesToData(StringCollection pths)
		{
			var sb = new StringBuilder();
			foreach(var itm in pths){
				sb.Append("<string>");
				sb.Append(itm);
				sb.Append("</string>");
				sb.Append(Environment.NewLine);
			}
			var s = String.Format("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<array>\n{0}</array>", sb.ToString());
			var data = Encoding.UTF8.GetBytes(s);
			return NSData.FromArray(data);
		}
		public StringCollection ClipboardFileList()
		{
			const string beg = "file://localhost";
			var pb = MonoMac.AppKit.NSPasteboard.GeneralPasteboard;
			var itms = pb.PasteboardItems;
			var res = new StringCollection();
			foreach(var i in itms){
				var id = i.GetDataForType("public.file-url");
				if(id != null){
					var path = id.ToString();
					path = Uri.UnescapeDataString(path);
					if(path.StartsWith(beg)){
						res.Add(path.Substring(beg.Length));
						Console.WriteLine (res[res.Count - 1]);
					}
				}
			}
			return res.Count > 0 ? res : null;
		}
		public bool ClipboardHasFiles()
		{
			return NSPasteboard.GeneralPasteboard.CanReadItemWithDataConformingToTypes(new[]{"public.file-url"});
		}
		public void InitNSMenu(MainWindow win)
		{
			var macm = new MacMenu(win);
			var mm = NSApplication.SharedApplication.MainMenu;
			var itms = mm.ItemArray();
			foreach(var itm in itms){
				if(itm.Title.Equals("edit", StringComparison.CurrentCultureIgnoreCase)){
					macm.SetEditMenu(itm);
					break;
				}}
		}
	}
	class MacMenu : NSMenuDelegate
	{
		MainWindow _win;
		NSMenuItem copy, paste, delete, rename;
		public MacMenu(MainWindow win)
		{
			_win = win;
		}
		public void SetEditMenu(NSMenuItem item)
		{
			var sub = new NSMenu("Edit");
			copy = new NSMenuItem("Copy", _win.DoCopy);
			paste = new NSMenuItem("Paste", _win.DoPaste);
			delete = new NSMenuItem("Delete", _win.DoDelete);
			var fold = new NSMenuItem("New Folder", _win.DoNewFolder);
			rename = new NSMenuItem("Rename", _win.BeginRename);
			var hist = new NSMenuItem("Edit History", _win.EditHistory);

			sub.AddItem(copy);
			sub.AddItem(paste);
			sub.AddItem(delete);
			sub.AddItem(NSMenuItem.SeparatorItem);
			sub.AddItem(fold);
			sub.AddItem(rename);
			sub.AddItem(NSMenuItem.SeparatorItem);
			sub.AddItem(hist);
			sub.AutoEnablesItems = false;

			item.Submenu = sub;
			sub.Delegate = this;
		}
		public override void MenuWillOpen (NSMenu menu)
		{
			var args = _win.GetMenuArgs();
			copy.Enabled = args.Copy;
			paste.Enabled = args.FilesAvailable;
			delete.Enabled = args.Delete;
			rename.Enabled = args.Rename;
		}
		public override void MenuWillHighlightItem (NSMenu menu, NSMenuItem item)
		{
//			Console.WriteLine ("NSMenuDelegate MenuWillHighlightItem");
		}
	}
}

